package com.lonni.rpc.core.register.zk;

import com.alibaba.fastjson2.JSON;
import com.lonni.rpc.core.register.AbstractServiceRegister;
import com.lonni.rpc.core.register.ServiceRegister;
import com.lonni.rpc.core.register.model.ServiceURL;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;

import java.net.InetSocketAddress;

import static org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent.Type.*;
import static org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent.Type.CHILD_UPDATED;

/**
 * 服务注册基类接口
 *
 * @author: Lonni
 * @date: 2024/7/9 0009 15:36
 */
@Slf4j
public class ZookeeperRegister extends AbstractServiceRegister {


    /**
     * 注册服务
     * 注册节点路径
     * /lonni-rpc/provider/com.xxx.server:分组:版本/ip/port
     *
     * @param url
     */
    @Override
    public void register(ServiceURL url) {
        //先注册根节点 (已经在初始化工具的时候注册了)

        try {
            // 在注册提供者主节点
//            ZKUtils.me.createNode(ZKUtils.me.getProviderPath(url), null);
            //在注册ip节点 写入数据
            ZKUtils.me.createNode(ZKUtils.me.getProviderPathForIpPort(url), JSON.toJSONString(url));
            super.register(url);
        } catch (Exception exception) {
            log.error("注册服务到zk失败", exception);
        }
    }

    /**
     * 删除服务实例
     *
     * @param url
     */
    @Override
    public void unRegister(ServiceURL url) {
        super.unRegister(url);
        //删除
        ZKUtils.me.deleteNode(ZKUtils.me.getProviderPathForIpPort(url));

    }

    /**
     * 监听
     *
     * @param url
     */
    @Override
    public void subscribe(ServiceURL url) throws Exception {
        final String path = ZKUtils.me.getProviderPath(url);
        PathChildrenCache cache = new PathChildrenCache(ZKUtils.me.client(), path, true);

        // 启动PathChildrenCache
        cache.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT);

        // 添加PathChildrenCacheListener监听器
        cache.getListenable().addListener(new PathChildrenCacheListener() {
            @Override
            public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
                final PathChildrenCacheEvent.Type type = event.getType();
                System.out.println("PathChildrenCache event: " + type);
                //监听删除节点事件
                if (type.equals(CHILD_REMOVED)) {
                    String path = event.getData().getPath();
                    log.info("监听到删除zk节点事件:{}", path);
//                    final URL url = parsePath(path);
//                    eventData = new DestroyEventData(url);
                } else if ((type.equals(CHILD_UPDATED)) || type.equals(CHILD_ADDED)) {
                    String path = event.getData().getPath();
                    byte[] bytes = client.getData().forPath(path);
                    log.info("监听到修改或则新增zk节点事件:{}", path);
                    Object o = com.alibaba.fastjson2.JSON.parseObject(bytes, ServiceURL.class);
                    //转换

                }
                //TODO 增加具体处理
            }

        });
    }
}
